define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    //设置弹窗宽高
    Fast.config.openArea = ['80%', '80%'];

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'cms/diyform/index',
                    add_url: 'cms/diyform/add',
                    edit_url: 'cms/diyform/edit',
                    del_url: 'cms/diyform/del',
                    multi_url: 'cms/diyform/multi',
//                    import_url: 'cms/diyform/import',
                    table: 'cms_model',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), operate: 'like'},
                        {field: 'chart_text', title: __('所属图分类'),operate: false},
                        {field: 'weigh', title: __('权重'),operate: false},
                        // {field: 'title', title: __('简介')},
//                        {field: 'table', title: __('Table')},
                        {
                            field: 'createtime',
                            sortable: true,
                            visible: false,
                            title: __('Createtime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'updatetime',
                            sortable: true,
                            visible: false,
                            title: __('Updatetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
        
                        {
                            field: 'datalist', title: __('Operate'), table: table, operate: false,
                            buttons: [
                                {
                                    name: 'content',
                                    text: __('数据列表'),
                                    classname: 'btn btn-xs btn-success btn-addtabs',
                                    icon: 'fa fa-file',
                                    url: 'cms/diydata/index/diyform_id/{ids}'
                                },
//                                 {
//                                     name: 'file',
//                                     text: __('导入excel'),
//                                     classname: 'btn btn-xs btn-info btn-fields btn-addtabs',
//                                     icon: 'fa fa-list',
//                                     url :"cms/diyform/uploadfile?form_id={ids}"
// //                                    url: 'cms/fields/index/source/diyform/source_id/{ids}'
//                                 },
                            ],
                            formatter: Table.api.formatter.buttons
                        },
//                        {field: 'status', title: __('Status'), searchList: {"normal": __('Normal'), "hidden": __('Hidden')}, formatter: Table.api.formatter.status},
                        {field: 'membership_price', title: __('Membership_price')},
                        {field: 'membership_duration', title: __('Membership_duration')},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {

            //获取标题拼音
            var si;
            $(document).on("keyup", "#c-name", function () {
                var value = $(this).val();
                if (value != '' && !value.match(/\n/)) {
                    clearTimeout(si);
                    si = setTimeout(function () {
                        Fast.api.ajax({
                            loading: false,
                            url: "cms/ajax/get_title_pinyin",
                            data: {title: value}
                        }, function (data, ret) {
                            $("#c-table").val("cms_diyform_" + data.pinyin);
                            $("#c-diyname").val(data.pinyin.substr(0, 100));
                            return false;
                        }, function (data, ret) {
                            return false;
                        });
                    }, 200);
                }
            });

            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                $.validator.config({
                    rules: {
                        diyname: function (element) {
                            if (element.value.toString().match(/^\d+$/)) {
                                return __('Can not be only digital');
                            }
                            if (!element.value.toString().match(/^[a-zA-Z0-9\-_]+$/)) {
                                return __('Please input character or digital');
                            }
                            return $.ajax({
                                url: 'cms/diyform/check_element_available',
                                type: 'POST',
                                data: {id: $("#diyform-id").val(), name: element.name, value: element.value},
                                dataType: 'json'
                            });
                        }
                    }
                });

                Form.api.bindevent($("form[role=form]"));
            }
        }
    };

    //监听选中数据图表的值,然后选中字段列表
    $(document).ready(function() {
        $('#c-chart_table_list_id').change(function() {
            var chart_table_list_id = $(this).val();
            //发送ajax
            // 在这里可以编写处理选中项变化的逻辑
            // console.log('选中的值为：' + chart_table_list_id);
            if (chart_table_list_id){
                $.ajax({
                    'type':'post',
                    'url':'cms/diyform/getFieldsList',
                    'dateType':'json',
                    'data':{
                        'chart_table_list_id':chart_table_list_id,
                    },
                    'success':function(res){
                        console.log(res);
                        if (res.code == 1){

                            var responseData = res.data;
                            //选择字段选项
                            document.getElementById('treeview').innerHTML = '';

                            // 双Y轴
                            const c_y_axial_2 = document.getElementById('c-y_axial_2');
                            c_y_axial_2.innerHTML = '';
                            c_y_axial_2.innerHTML = '<option value="">请选择</option>';
                            for (const key in responseData) {
                                if (responseData.hasOwnProperty(key)) {
                                    //更换字段选择
                                    const value = responseData[key];
                                    const checkboxInput = document.createElement('div');
                                    checkboxInput.innerHTML = `
                                        <div class="checkbox_input">
                                            <div>
                                                <input type="checkbox" name="row[${key}]" value="${key}" />
                                                <label>${value}</label>
                                            </div>
                                            <div>
                                                <input class="fields_name" type="text" name="row[${key}_as]" value="" placeholder="请输入别名">
                                            </div>
                                        </div>
                                    `;
                                    document.getElementById('treeview').appendChild(checkboxInput);

                                    //更换第二个Y轴选择
                                    // 添加选项到第二个Y轴选择
                                    // 创建<option>元素
                                    const optionElement = document.createElement("option");
                                    optionElement.value = key;
                                    optionElement.text = value;

                                    // 将<option>元素添加到<select>元素中
                                    c_y_axial_2.appendChild(optionElement);
                                }
                            }
                        }else{
                            layer.msg(res.msg, {icon: 5});
                        }
                    }
                });
            }
        });
    });

    //监听双Y轴选中项
    if (document.getElementById("c-y_axial_2")){
        document.getElementById("c-y_axial_2").addEventListener("change", function() {
            const selectedValue = this.value; // 获取当前选中的值
            const selectedText = this.options[this.selectedIndex].text; // 获取当前选中的文本
            //console.log("选中的值：" + selectedValue);
            //console.log("选中的文本：" + selectedText);
            // 在这里执行你想要的操作
            const checkboxInputs = document.querySelectorAll("#treeview .checkbox_input input[type='checkbox']"); // 获取所有位于 #treeview 下的 .checkbox_input 中的复选框
            const selectedItems = Array.from(checkboxInputs).filter(input => input.checked).map(input => input.value); // 获取选中的项的值
            //console.log(888,selectedItems); // 打印选中的项的值
            //判断双Y轴选中值是否存在与"字段列表"中的勾选字段
            if (selectedItems.includes(selectedValue)) {
                //console.log(selectedValue + " 在选中的项中");
            } else {
                //console.log(selectedValue + " 不在选中的项中");
                var msg = '请先勾选"字段列表"中的' + '"' + selectedText + '"'
                layer.msg(msg, {icon: 5});
            }
        });
    }


    return Controller;
});
